<template>
  <div class="avatar-page">
    <el-card>
      <template #header>
        <span style="font-size: 16px; color: #131523; font-weight: 500;">更换头像</span>
      </template>
      <div class="avatar-body">
        <el-image
        style="width: 226px;height: 226px;"
        :src="imgSrc"
        ></el-image>
        <el-upload
        action=""
        :show-file-list="false"
        :http-request="uploadAvatar"
        style="margin-top: 20px; margin-bottom: 20px;"
        >
          <el-button icon="el-icon-plus" style="background-color: #4F81FF;color: rgba(255,255,255,0.90);">选择头像</el-button>
          <el-button icon="el-icon-upload2" style="background-color: #EAECF5; color: #0052D9;">上传图片</el-button>
        </el-upload>
      </div>
    </el-card>
  </div>
</template>

<script>
import { updateUserAvatar, getUserInfo } from '@/api/user'
export default {
  name: 'ChangeAvatar',
  data () {
    return {
      imgSrc: require('@/assets/images/avatar.jpg'),
      avatar: ''
    }
  },
  created () {
    this.getUpdateUserAvatar()
  },
  methods: {
    // 获取更新后的头像，并将个人中心和欢迎区域图片一起更新
    async getUpdateUserAvatar () {
      const res = await getUserInfo()
      // console.log(res)
      this.$store.commit('user/setUserAvatar', res.data.user_pic)
    },
    uploadAvatar (file) {
      console.log(file)
      const reader = new FileReader()
      // 异步读取文件内容，并返回url
      reader.readAsDataURL(file.file)
      // 触发onload事件，获取异步读取文件结果
      reader.onload = async e => {
        this.imgSrc = e.target.result
        // console.log(e.target.result)
        const res = await updateUserAvatar({
          avatar: this.imgSrc
        })

        // 调用获取用户信息函数
        this.getUpdateUserAvatar()
        // console.log(res)
        this.$message.success(res.message)
      }

      // console.log(this.imgSrc)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-card__header {
  padding-top: 23px;
  padding-bottom: 23px;
  padding-left: 30px;
}
::v-deep .el-card__body {
  padding-top: 30px;
  padding-left: 30px;
}
</style>
